#include "../include/muduo/net/TcpServer.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/TcpConnection.h"

#include <iostream>
#include <unordered_map>
#include <functional>

class TranslateServer
{
public:
    TranslateServer(int port)
        :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), 
            "TranslateServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, 
            std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        _server.start();
        _baseloop.loop();
    }
private:
    // onCommection 是一个在连接建立成功，以及关闭的时候使用
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected() == true)
        {
            std::cout << "新连接建立成功" << std::endl;
        }
        else
        {
            std::cout << "新连接关闭" << std::endl;
        }
    }
    std::string translate(const std::string &str)
    {
        std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"signal", "信号"},
            {"connect", "连接"},
            {"lib", "库"}
        };
        auto it = dict_map.find(str);
        if(it == dict_map.end())
        {
            return "未知单词";
        }
        return it->second;
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        // 通信连接收到请求时回调函数
        // 1. 从buf中取出数据
        std::string str = buf->retrieveAllAsString();
        // 2. 调用函数接口进行翻译
        std::string resp = translate(str);
        // 3. 对客户端进行响应结果
        conn->send(resp);
    }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer server(8080);
    server.start();
    return 0;
}
